package me.xiaoyan.java.spring.controller;

import me.xiaoyan.java.spring.po.Account;
import me.xiaoyan.java.spring.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/account")
public class AccountController extends BaseController {
    private AccountService accountService;

    @Autowired
    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

    @RequestMapping("/accounts")
    public String showAccountsList(Model model) {
        List<Account> all = accountService.findAll();
        model.addAttribute("accountList", all);
        return "accounts";
    }

    @PostMapping("/login")
    public String login(Account account, Model model) {
        account = accountService.login(account);
        if(account == null){
            return showMessage(model, "登录失败:用户名或者密码错误", "../login.html", 3);
        }
        return showMessage(model, "登录成功", "./accounts", 3);
    }

    @PostMapping("/reg")
    public String signUp(Account account, Model model) {
       try{
           if (accountService.create(account)) {
               return showMessage(model, "注册成功", "../login.html", 10);
           }
           return showMessage(model, "注册失败", "../reg.html", 10);
       }catch(RuntimeException e){
           return showMessage(model, e.getMessage(), "../reg.html", 10);
       }
    }
}
